/****************************************************************
*  * *Process the common configure interface
*  * *
*  * *file name:logmgr.h
*  * *
*  * *Copyright (C)2012 Cisco webex.
*  * *All rights reserved
*  * *
*  * *Author:zhenye
*  * *Date  :2013-04-27
*  * *
*  * ****************************************************************/

#include <string>
#include "mct_system.h"
#include "logfile.h"
#include "logmgr.h"

static const ULONG LOG_BUFF_MAX_LEN = 4096;

VOID DumpMsgNew(BOOL_T bstdout, LONG nLevel, CHAR *pcFile, LONG lineNum, std::string lpszFormat, ...)
{
    CHAR szText[LOG_BUFF_MAX_LEN] = {0};
    CHAR szTextTemp[LOG_BUFF_MAX_LEN] = {0};

    if (NULL == pcFile)
    {
        return;
    }

    va_list va;
    va_start(va, lpszFormat);
    vsnprintf(szTextTemp, LOG_BUFF_MAX_LEN, lpszFormat.c_str(), va);
    va_end(va);

    if (BOOL_TRUE == bstdout)
    {
        fprintf(stdout, "%s\r\n", szTextTemp);
    }

    MCT_snprintf(szText, LOG_BUFF_MAX_LEN, "[%d][%s:%lu] =>%s", (LONG) MCT_getpid(), pcFile, lineNum, szTextTemp);

    CLogger*pLog=CLogger::getInstance();
    if(pLog)
    {
        pLog->outMsg(szText, nLevel);
    }
}

#ifndef WIN32
/* get absolute path of the module */
static VOID GetModuleFileName (VOID*handle, CHAR *szPath, LONG nMaxLen)
{
    LONG count = -1;
    CHAR szProcPath[MAX_ABSOLUTE_PATH_LEN] = {0};

    MCT_ASSERT(NULL != szPath);
    MCT_ASSERT(0 < nMaxLen);

    MCT_snprintf(szProcPath, MAX_ABSOLUTE_PATH_LEN, "/proc/%lu/exe", MCT_getpid());

    count = MCT_readlink(szProcPath, szPath, nMaxLen);

    if ((count< 0) || (count >= nMaxLen))
    {
       szPath[0] = 0;
       return;
    }

    szPath[nMaxLen - 1] = 0;

    return;
}
#endif

CHAR * GetProgramPath(LONG level, CHAR *szPath, LONG nMaxLen)
{
    if ((NULL == szPath) || (0 >= nMaxLen))
    {
        return NULL;
    }

    GetModuleFileName(NULL, szPath, nMaxLen);

    LONG len = MCT_strlen(szPath);
    for(LONG i = len - 1; i > 0; i--)
    {
        if((szPath[i] != '/') && (szPath[i] != '\\'))
        {
            szPath[i] = 0;
        }
        else
        {
            if(level--)
            {
                szPath[i] = 0;
            }
            else
            {
                break ;
            }
        }
    }

    /* if not exist path, fill with root dir  */
    if (0 == *szPath)
    {
        MCT_strncpy(szPath, "/", nMaxLen - 1);
    }

    return szPath;
}
